<!DOCTYPE html>
{include file='head_hooks.html'}

<head>
  <title>{$project->name} Dashboard | Protoweb</title>

  {include file='head_scripts.html'}

  <script>
    var conns = [];
  </script>

</head>

<body>
  {include file='body_hooks.html'}

  {include file='navbar.html'}

  <div class="container-fluid">

    {include file='messages.html'}
    
    <div class="row-fluid plumb_container">

        <div id="plumb_zoom" class="btn-group btn-group-vertical">
          <button id="zoom_in" type="button" class="btn"><i class="icon-plus"></i></button>
          <button id="zoom_out" type="button" class="btn"><i class="icon-minus"></i></button>
        </div>

        <div id="plumb" class="printable">   

            {foreach from=$project->entity item="entity"}

              {include file='project_dashboard_entity.html'}

              <script>
                {foreach from=$entity->getHasMany() item="relation" name=list_hasmany}
                    conns.push(["{$entity->id}","{$relation->id}"]);
                {/foreach}
              </script>
            
            {foreachelse}

              <p>No hay Entidades definidas</p>

            {/foreach}
            <!-- entity -->

        </div>
        <!-- plumb -->

    </div>
    <!-- row -->

  </div> <!-- /container -->

  {include file='footer_scripts.html'}

  <!--
  <script type="text/javascript" src="http://jsplumb.org/js/jquery.ui.touch-punch.min.js"></script>
  <script src="http://threedubmedia.com/inc/js/jquery.event.drag-2.2.js"></script>
  -->
  <script type='text/javascript' src='assets/js/libs/jquery.jsPlumb-1.3.16-all-min.js'></script>

    <!--  plumb code -->
    
    {literal}
    <script>

    var connColor = function() { return "rgb(120,120,120)"; };

    jsPlumb.bind("ready", function() {
      jsPlumb.setRenderMode(jsPlumb.SVG);
      jsPlumbPW.init();
    });

      
    window.jsPlumbPW = { 
    
      init: function() {

        jsPlumb.setSuspendDrawing(true);
                
        jsPlumb.importDefaults({
          Endpoint : ["Dot", {radius:2}],
          HoverPaintStyle : {strokeStyle:"red", lineWidth:2 },
          ConnectionOverlays : [
            [ "Arrow", { 
              location:1,
              id:"arrow",
                        length:10,
                        foldback:0
            } ]
          ]
        });

        // initialize draggable elements
        jsPlumb.draggable(jsPlumb.getSelector(".entity"));
        jQuery(".entity").draggable({
          handle: ".popover-title",

          stop: function( event, ui ) {
            updateEntity(this);
         }
        });

                
        // bind a click listener to remove each connection
        jsPlumb.bind("click", function(conn) { 
          if (confirm("Remove connection?")) {
            removeRelation(conn); 
          }
        });
          
        jsPlumbPW.initEndpoints(connColor);

        jsPlumb.makeTarget(jsPlumb.getSelector(".entity"), {
          dropOptions:{ hoverClass:"dragHover" },
          anchor:"Continuous"     
        });

        // catch elements defined on conns array and draw it on the screen
        for (var i = 0; i < conns.length; i++) {
          // conecto dos elementos existentes
          jsPlumb.connect({ 
            source: conns[i][0], 
            target: conns[i][1]
          });
        };

        // bind a listener on add connections
        jsPlumb.bind("jsPlumbConnection", function(conn) {
          addRelation(conn);
        });

        //jsPlumb.repaintEverything();
        jsPlumb.setSuspendDrawing(false, true);

      } // init
    }; // jsPlumbPW

     jsPlumbPW.initEndpoints = function(connColor) {
        jQuery(".ep").each(function(i,e) {
        var p = jQuery(e).parent();
        jsPlumb.makeSource(jQuery(e), {
          parent:p,
          anchor:"Continuous",
          connector:[ "Flowchart", { } ],
          connectorStyle:{ strokeStyle:connColor(), lineWidth:2 }
        });
      });   
      }; // initEndpoints

      jsPlumbPW.addElement = function(id) {
        jQuery("#plumb").append('<div class="entity" id="'+id+'"><h1>'+id+'</h1><div class="ep"></div></div>');
        
        jsPlumbPW.initEndpoints(connColor);

        jsPlumb.makeTarget(jsPlumb.getSelector(".entity"), {
          dropOptions:{ hoverClass:"dragHover" },
          anchor:"Continuous"     
        });

        jsPlumb.draggable(jsPlumb.getSelector(".entity"));

      }; // addElement


      jQuery(function(){

        jQuery(".entity:not('.entity-minimized')").each(function() {
          getEntityContent(this);
        });

        jQuery('#zoom_in').on('click', function() {
          var zoom = parseFloat(jQuery("#plumb").css("zoom"));
          jQuery("#plumb").css("zoom", zoom + 0.1);
        });

        jQuery('#zoom_out').on('click', function() {
          var zoom = parseFloat(jQuery("#plumb").css("zoom"));
          jQuery("#plumb").css("zoom", zoom - 0.1);
        });

        jQuery('.btn-minimize').on('click', function() {
          event.preventDefault();
          //event.stopPropagation();

          var entity = jQuery(this).parents('.entity');
          var res = entity.toggleClass('entity-minimized');

          if (entity.hasClass('entity-minimized')) {
            entity.attr('data-status','entity-minimized');
          }
          else {
            entity.attr('data-status','');
            getEntityContent(entity[0]);
          }
          
          updateEntity(entity[0]);
          //jsPlumb.repaintEverything();
        }); // minimize - restore


        
        jQuery('.entity').on('mousedown', function() {
          var index_highest = 0;
          $(".entity").each(function() {
              // always use a radix when using parseInt
              var index_current = parseInt($(this).css("zIndex"), 10);
              if (index_current > index_highest) {
                  index_highest = index_current;
              }
          });

          $(this).css('z-index',index_highest+1);
        });

      }); // jQuery Document Ready

    </script>
    {/literal}

    <script>
         
      function getEntityContent(element) {
        console.log(element);
        var element_id = element.id;
        jQuery.get('entities/content/'+element.id+'/', function(data) {
          jQuery('.entity#'+element_id).find(".popover-content").html(data);
        });
      }

      function updateEntity(entity) {
        var status = entity.getAttribute('data-status');

        jQuery.ajax({
          type: 'POST',
          url: '{base_url()}entities/update_status/',
          data: { 
            "style" : jQuery(entity).attr("style"),
            "entity": entity.id,
            "class": status
          }
        });
      }

      function removeRelation(conn) {
        jQuery.ajax({
          type: 'POST',
          url: '{base_url()}entities/remove_relation/',
          data: { 
            "source" : conn.sourceId,
            "target" : conn.targetId
          }
        });
        jsPlumb.detach(conn);
      }

      function addRelation(conn) {
        jQuery.ajax({
          type: 'POST',
          url: '{base_url()}entities/add_relation/',
          data: { 
            "source" : conn.sourceId,
            "target" : conn.targetId
          }
        });
      }
    </script>

    <!-- Create Entity's Modal -->
    <div class="modal hide fade" id="entities_create" tabindex="-1" role="dialog">
      <div class="modal-body reset-modal-body"></div>
    </div>

    <!-- Create Action's Modal -->
    <div class="modal hide fade" id="actions_create" tabindex="-1" role="dialog">
      <div class="modal-body reset-modal-body"></div>
    </div>

    <!-- Create View's Modal -->
    <div class="modal hide fade" id="views_create" tabindex="-1" role="dialog">
      <div class="modal-body reset-modal-body"></div>
    </div>

    <!-- Edit Model's Modal -->
    <div class="modal hide fade" id="entities_edit" tabindex="-1" role="dialog">
      <div class="modal-body reset-modal-body"></div>
    </div>

    <!-- Generate CRUD's Modal -->
    <div class="modal hide fade" id="entities_generate_crud" tabindex="-1" role="dialog">
      <div class="modal-body reset-modal-body"></div>
    </div>

    <script>
      // Will Force to reload contents
      $('body').on('hidden', '.modal', function () {
        $(this).removeData('modal');
      });
    </script>

  </body>

</html>
